const link = document.createElement('a');

function save(blob: Blob, filename: string) {
  if (link.href) {
    URL.revokeObjectURL(link.href);
  }

  link.href = URL.createObjectURL(blob);
  link.download = filename || 'data.json';
  link.dispatchEvent(new MouseEvent('click'));
}

function saveArrayBuffer(buffer: ArrayBuffer, filename: string) {
  save(new Blob([buffer], { type: 'application/octet-stream' }), filename);
}

function saveString(text: string, filename: string) {
  save(new Blob([text], { type: 'text/plain' }), filename);
}

function formatNumber(number: number) {
  return new Intl.NumberFormat('en-us', { useGrouping: true }).format(number);
}

export const utils = {
  save: save,
  saveArrayBuffer: saveArrayBuffer,
  saveString: saveString,
  formatNumber: formatNumber,
};
